/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package jogo;

import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.util.Random;

/**
 *
 * @author Pxcvsa
 */
public class Jogo extends Applet implements Runnable, KeyListener {

    /**
     * @param args the command line arguments
     */
    //  public static void main(String[] args) {
    // TODO code application logic here
    //  }
    //Tarefa iniciar o jogo
    Thread gameloop;

    //use this as a double buffer
    BufferedImage backbuffer;

    //the main drawing object for the back buffer
    Graphics2D g2d;

    //toggle for drawing object for the back buffer
    boolean showBounds = false;

    //create the asteroid array
    int ASTEROIDS = 20;
    Asteroid[] ast = new Asteroid[ASTEROIDS];

    //create the bullet array
    int BULLETS = 10;
    Bullet[] bullet = new Bullet[BULLETS];
    int currentBullet = 0;

    //the player's ship
    Ship ship = new Ship();

    //create the identity transform (0,0)
    AffineTransform identity = new AffineTransform();

    //create a random number generator
    Random rand = new Random();

    //Evento init()
    @Override
    public void init() {
        //create the back buffer for smooth graphics
        backbuffer = new BufferedImage(640, 480, BufferedImage.TYPE_INT_RGB);
        g2d = backbuffer.createGraphics();

        //Criar o jogador
        ship.setX(320);
        ship.setY(240);

        //Criar os tiros
        for (int n = 0; n < BULLETS; n++) {
            bullet[n] = new Bullet();
        }

        //Criando os asteroides
        for (int n = 0; n < ASTEROIDS; n++) {
            ast[n] = new Asteroid();
            ast[n].setRotationVelocity(rand.nextInt(3) + 1);
            ast[n].setX((double) rand.nextInt(600) + 20);
            ast[n].setY((double) rand.nextInt(440) + 20);
            ast[n].setMoveAngle(rand.nextInt(360));
            double ang = ast[n].getMoveAngle() - 90;        
            ast[n].setVelX(calcAngleMoveX(ang));
            ast[n].setVelY(calcAngleMoveY(ang));

            //Start the user input listener
            addKeyListener(this);

        }
    }

    public void update(Graphics g) {
        //Start off transforms at identity
        g2d.setTransform(identity);

        //erase the background
        g2d.setPaint(Color.BLACK);
        g2d.fillRect(0, 0, getSize().width, getSize().height);

        //print some status information
        g2d.setColor(Color.white);
        g2d.drawString("Ship: " + Math.round(ship.getX()) + "," + Math.round(ship.getY()), 5, 10);
        g2d.drawString("Move angle: " + Math.round(ship.getMoveAngle() + 90), 5, 25);
        g2d.drawString("Face angle: " + Math.round(ship.getFaceAngle()), 5, 40);

        //draw the game graphics
        drawShip();
        drawBullets();
        drawAsteroids();

        //repaint the applet window
        paint(g);
    }

    private void drawShip() {
        g2d.setTransform(identity);
        g2d.translate(ship.getX(), ship.getY());
        g2d.rotate(Math.toRadians(ship.getFaceAngle()));
        g2d.setColor(Color.ORANGE);
        g2d.fill(ship.getShape());
    }

    private void drawBullets() {
        for (int n = 0; n < BULLETS; n++) {
            if (bullet[n].isAlive()) {
                g2d.setTransform(identity);
                g2d.translate(bullet[n].getX(), bullet[n].getY());
                g2d.setColor(Color.MAGENTA);
                g2d.draw(bullet[n].getShape());
            }
        }
    }

    private void drawAsteroids() {
        for (int n = 0; n < ASTEROIDS; n++) {
            if (ast[n].isAlive()) {
                g2d.setTransform(identity);
                g2d.translate(ast[n].getX(), ast[n].getY());
                g2d.rotate(Math.toRadians(ast[n].getMoveAngle()));
                g2d.setColor(Color.DARK_GRAY);
                g2d.fill(ast[n].getShape());
            }
        }
    }

    public void paint(Graphics g) {
        g.drawImage(backbuffer, 0, 0, this);
    }

    public void start() {
        gameloop = new Thread(this);
        gameloop.start();
    }

    @Override
    public void run() {
        Thread t = Thread.currentThread();
        while (t == gameloop) {
            try {
                gameUpdate();
                Thread.sleep(20);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            repaint();
        }
    }

    public void stop() {
        gameloop = null;
    }

    public void gameUpdate() {
        updateShip();
        updateBullets();
        updateAsteroids();
        checkCollisions();
    }

    public void updateShip() {
        //update ship's X position
        ship.incX(ship.getVelX());

        //wrap around left/right
        if (ship.getX() < -10) {
            ship.setX(getSize().width + 10);
        } else if (ship.getX() > getSize().width + 10) {
            ship.setX(-10);
        }

        //wrap around top/botton
        if (ship.getY() < -10) {
            ship.setY(getSize().width + 10);
        } else if (ship.getY() > getSize().width + 10) {
            ship.setY(-10);
        }

    }

    private void updateBullets() {
        //move each of the bullets
        for (int n = 0; n < BULLETS; n++) {
            //is this bullet being used?
            if (bullet[n].isAlive()) {
                //update bullet's x position
                bullet[n].incX(bullet[n].getVelX());

                //bullet disappears at left right edge
                if (bullet[n].getX() < 0 || bullet[n].getX() > getSize().width) {
                    bullet[n].setAlive(false);
                }
                //update bullet's y position
                bullet[n].incY(bullet[n].getVelY());

                //bullet disappears at left right edge
                if (bullet[n].getY() < 0 || bullet[n].getY() > getSize().width) {
                    bullet[n].setAlive(false);
                }
            }
        }
    }

    private void updateAsteroids() {
        //move a d rotate the asteroids
        for (int n = 0; n < ASTEROIDS; n++) {
            //is this asteroid being used?
            if (ast[n].isAlive()) {
                //update the asteroid's X value
                ast[n].incX(ast[n].getVelX());
                //wrao the asteroid at screen edges
                if (ast[n].getX() < -20) {
                    ast[n].setX(getSize().width + 20);
                } else if (ast[n].getX() > getSize().width + 20) {
                    ast[n].setX(-20);
                }

                //update the asteroid's Y value
                ast[n].incY(ast[n].getVelY());
                //wrao the asteroid at screen edges
                if (ast[n].getY() < -20) {
                    ast[n].setY(getSize().width + 20);
                } else if (ast[n].getY() > getSize().width + 20) {
                    ast[n].setY(-20);
                }

                //update asteroid rotation
                ast[n].incMoveAngle(ast[n].getRotationVelocity());

                //keep the angle within 0 -359
                if (ast[n].getMoveAngle() < 0) {
                    ast[n].setMoveAngle(360 - ast[n].getRotationVelocity());
                } else if (ast[n].getMoveAngle() > 360) {
                    ast[n].setMoveAngle(ast[n].getRotationVelocity());
                }

            }
        }

    }

    private void checkCollisions() {
        //iterate through the asteroids array
        for (int m = 0; m < ASTEROIDS; m++) {
            //is this asteroid being used?
            if (ast[m].isAlive()) {
                //Verifica colisao com o tiro
                for (int n = 0; n < BULLETS; n++) {
                    //is this bullet being used?
                    if (bullet[n].isAlive()) {
                        //perform the collision test
                        if (ast[m].getBounds().contains(bullet[n].getX(), bullet[n].getY())) {
                            bullet[n].setAlive(false);
                            ast[m].setAlive(false);
                            continue;
                        }
                    }
                }
                //Verifica colisao com jogador
                if (ast[m].getBounds().intersects(ship.getBounds())) {
                    ast[m].setAlive(false);
                    ship.setX(320);
                    ship.setY(240);
                    ship.setFaceAngle(0);
                    ship.setVelX(0);
                    ship.setVelY(0);
                    continue;
                }
            }
        }
    }
    
    @Override
    public void keyPressed(KeyEvent k) {
        int keyCode = k.getKeyCode();
        switch (keyCode) {
            case KeyEvent.VK_LEFT:
                ship.incFaceAngle(-5);
                if(ship.getFaceAngle() < 0)
                    ship.setFaceAngle(360-5);
                break;
              
            case KeyEvent.VK_RIGHT:
                ship.incFaceAngle(5);
                if(ship.getFaceAngle() > 360)
                    ship.setFaceAngle(5);
                break;
           
            case KeyEvent.VK_UP:
                ship.setMoveAngle(ship.getFaceAngle() - 90);
                ship.incVelX(calcAngleMoveX(ship.getMoveAngle()) * 0.1);
                ship.incVelY(calcAngleMoveY(ship.getMoveAngle()) * 0.1);
                break;
                
            case KeyEvent.VK_CONTROL:
            case KeyEvent.VK_ENTER:
            case KeyEvent.VK_SPACE:
                currentBullet++;
                if(currentBullet > BULLETS - 1)
                    currentBullet = 0;
                bullet[currentBullet].setAlive(true);
                
                bullet[currentBullet].setX(ship.getX());
                bullet[currentBullet].setY(ship.getY());
                bullet[currentBullet].setMoveAngle(ship.getFaceAngle() - 90);
                
                double angle = bullet[currentBullet].getMoveAngle();
                double svx = ship.getVelX();
                double svy = ship.getVelY();
                
                bullet[currentBullet].setVelX(svx + calcAngleMoveX(angle) * 2);
                bullet[currentBullet].setVelY(svy + calcAngleMoveY(angle) * 2);
                break;

        }
    }

    @Override
    public void keyTyped(KeyEvent ke) {
        
    }

    @Override
    public void keyReleased(KeyEvent ke) {
        
    }
    
    public double calcAngleMoveX(double angle) {
        return (double) (Math.cos(angle * Math.PI / 180));
    }
    
    public double calcAngleMoveY(double angle) {
        return (double) (Math.sin(angle * Math.PI / 180));
    }

}
